import React, { useState, useEffect, useMemo } from "react";
import { flushSync } from "react-dom";
import { connect } from "react-redux";
import action from "../store/action";

import api from "../api";
import "./styles/Detail.scss";

import {
  LeftOutline,
  MessageOutline,
  LikeOutline,
  StarOutline,
  MoreOutline,
} from "antd-mobile-icons";
import { Badge } from "antd-mobile";

function Detail(props) {
  let {
    usp,
    navigate,
    store: { storeList },
    getStoreList,
    user: { userInfo },
    getUserInfo,
    removeStoreListById,
  } = props;

  const [newsInfo, setNewsInfo] = useState("");
  const [extra, setExtra] = useState(null);
  const [isStore, setIsStore] = useState(false);
  const id = usp.get("id");
  let link;

  useEffect(() => {
    getNewsInfo();
    getExtra();
    return () => {
      if (link) document.head.removeChild(link);
    };
  }, []);

  useEffect(() => {
    (async () => {
      if (!userInfo) {
        let { info } = await getUserInfo();
        userInfo = info;
      }
      if (userInfo && !storeList) {
        getStoreList();
      }
    })();
  }, []);
  useMemo(() => {
    if (storeList) {
      let isStore = storeList.some((item) => {
        return item.news.id === id;
      });
      setIsStore(isStore);
    }
  }, [storeList, id]);

  async function getNewsInfo() {
    const result = await api.queryNewsInfo(id);
    flushSync(() => {
      setNewsInfo(result);
      handlerStyle(result);
    });
    handlerImg(result);
  }
  async function getExtra() {
    const id = usp.get("id");
    try {
      const result = await api.queryStoryExtra(id);
      setExtra(result);
    } catch (error) {}
  }

  // 创建样式
  function handlerStyle(result) {
    let { css } = result;
    if (!Array.isArray(css)) return;
    css = css[0];
    if (!css) return;
    link = document.createElement("link");
    link.rel = "stylesheet";
    link.href = css;
    document.head.appendChild(link);
  }
  function handlerImg(result) {
    const imgPlaceHolder = document.querySelector(".img-place-holder");
    const mark = document.createElement("div");

    const { image, title } = result;
    if (!image) return;

    let tempImg = new Image();
    tempImg.src = image;
    tempImg.onload = () => {
      imgPlaceHolder.appendChild(tempImg);
      if (!title) return;
      mark.className = "mark";
      mark.style.position = "absolute";
      mark.textContent = title;
      imgPlaceHolder.appendChild(mark);
    };
    tempImg.onerror = () => {
      const parent = imgPlaceHolder.parentNode;
      parent.parentNode.removeChild(imgPlaceHolder);
      imgPlaceHolder.parent.removeChild(mark);
    };
  }

  async function handleStore() {
    if (isStore) {
      const { code } = await api.storeRemove(id);
      if (code === 0) setIsStore(false);
      removeStoreListById(id);
    } else {
      const { code } = await api.store(id);
      if (code === 0) setIsStore(true);
      getStoreList();
    }
  }

  return (
    <div className="detail-container">
      <div
        className="news_content"
        dangerouslySetInnerHTML={{
          __html: newsInfo.body,
        }}
      ></div>
      <div className="detail-tabbar">
        <div className="back-icon" onClick={() => navigate(-1)}>
          <LeftOutline />
        </div>
        <div className="icons">
          <Badge content={extra ? extra.comments : 0}>
            <MessageOutline />
          </Badge>
          <Badge content={extra ? extra.popularity : 0}>
            <LikeOutline />
          </Badge>
          <span className={isStore ? "stored" : ""} onClick={handleStore}>
            <StarOutline />
          </span>
          <span>
            <MoreOutline />
          </span>
        </div>
      </div>
    </div>
  );
}

export default connect((state) => state, {
  ...action.store,
  ...action.user,
})(Detail);
